home *** CD-ROM | disk | FTP | other *** search
/ HyperLib 1997 Winter - Disc 1 / HYPERLIB-1997-Winter-CD1.ISO.7z / HYPERLIB-1997-Winter-CD1.ISO / オンラインウェア / UTIL / PL 2.0 SupplementDoc Folder.sit / PL 2.0 SupplementDoc Folder / Documentation / Chapter 27. Pretty Printing < prev    next >
Text File  |  1995-03-28  |  49KB  |  1,018 lines

  1. Common Lisp the Language, 2nd Edition
  2. -------------------------------------------------------------------------------
  3.  
  4. 27. Pretty Printing
  5.  
  6. by Richard C. Waters
  7.  
  8. [change_begin]
  9. PREFACE: X3J13 voted in January 1989 (PRETTY-PRINT-INTERFACE)   to adopt a
  10. facility for user-controlled pretty printing as a part of the forthcoming draft
  11. Common Lisp standard. This facility is the culmination of thirteen years of
  12. design, testing, revision, and use of this approach.
  13.  
  14. This chapter presents the bulk of the Common Lisp pretty printing
  15. specification, written by Richard C. Waters. I have edited it only very lightly
  16. to conform to the overall style of this book.
  17.  
  18.      - Guy L. Steele Jr.
  19.  
  20. [change_end]
  21. -------------------------------------------------------------------------------
  22.  
  23.    *  Introduction
  24.    *  Pretty Printing Control Variables
  25.    *  Dynamic Control of the Arrangement of Output
  26.    *  Format Directive Interface
  27.    *  Compiling Format Control Strings
  28.    *  Pretty Printing Dispatch Tables
  29.  
  30. -------------------------------------------------------------------------------
  31.  
  32. 27.1. Introduction
  33.  
  34. [change_begin]
  35. Pretty printing has traditionally been a black box process, displaying program
  36. code using a set of fixed layout rules. Its utility can be greatly enhanced by
  37. opening it up to user control. The facilities described in this chapter provide
  38. general and powerful means for specifying pretty-printing behavior.
  39.  
  40. By providing direct access to the mechanisms within the pretty printer that
  41. make dynamic decisions about layout, the macros and functions
  42. pprint-logical-block, pprint-newline, and pprint-indent make it possible to
  43. specify pretty printing layout rules as a part of any function that produces
  44. output. They also make it very easy for the function to support detection of
  45. circularity and sharing and abbreviation based on length and nesting depth.
  46. Using the function set-pprint-dispatch, one can associate a user-defined pretty
  47. printing function with any type of object. A small set of new format directives
  48. allows concise implementation of user-defined pretty-printing functions.
  49. Together, these facilities enable users to redefine the way code is displayed
  50. and allow the full power of pretty printing to be applied to complex
  51. combinations of data structures.
  52.  
  53. -------------------------------------------------------------------------------
  54. Implementation note: This chapter describes the interface of the XP pretty
  55. printer. XP is described fully in [54], which also explains how to obtain a
  56. portable implementation. XP uses a highly efficient linear-time algorithm. When
  57. properly integrated into a Common Lisp, this algorithm supports pretty printing
  58. that is only fractionally slower than ordinary printing.
  59. -------------------------------------------------------------------------------
  60.  
  61. [change_end]
  62.  
  63. -------------------------------------------------------------------------------
  64.  
  65. 27.2. Pretty Printing Control Variables
  66.  
  67. [change_begin]
  68. The function write accepts keyword arguments named :pprint-dispatch,
  69. :miser-width, :right-margin, and :lines, corresponding to these variables.
  70.  
  71. [Variable]
  72. *print-pprint-dispatch*
  73.  
  74. When *print-pretty* is not nil, printing is controlled by the `pprint dispatch
  75. table' stored in the variable *print-pprint-dispatch*. The initial value of
  76. *print-pprint-dispatch* is implementation-dependent and causes traditional
  77. pretty printing of Lisp code. The last section of this chapter explains how the
  78. contents of this table can be changed.
  79.  
  80. [Variable]
  81. *print-right-margin*
  82.  
  83. A primary goal of pretty printing is to keep the output between a pair of
  84. margins. The left margin is set at the column where the output begins. If this
  85. cannot be determined, the left margin is set to zero.
  86.  
  87. When *print-right-margin* is not nil, it specifies the right margin to use when
  88. making layout decisions. When *print-right-margin* is nil (the initial value),
  89. the right margin is set at the maximum line length that can be displayed by the
  90. output stream without wraparound or truncation. If this cannot be determined,
  91. the right margin is set to an implementation-dependent value.
  92.  
  93. To allow for the possibility of variable-width fonts, *print-right-margin* is
  94. in units of ems-the width of an ``m'' in the font being used to display
  95. characters on the relevant output stream at the moment when the variables are
  96. consulted.
  97.  
  98. [Variable]
  99. *print-miser-width*
  100.  
  101. If *print-miser-width* is not nil, the pretty printer switches to a compact
  102. style of output (called miser style) whenever the width available for printing
  103. a substructure is less than or equal to *print-miser-width* ems. The initial
  104. value of *print-miser-width* is implementation-dependent.
  105.  
  106. [Variable]
  107. *print-lines*
  108.  
  109. When given a value other than its initial value of nil, *print-lines* limits
  110. the number of output lines produced when something is pretty printed. If an
  111. attempt is made to go beyond *print-lines* lines, `` ..'' (a space and two
  112. periods) is printed at the end of the last line followed by all of the suffixes
  113. (closing delimiters) that are pending to be printed.
  114.  
  115. (let ((*print-right-margin* 25) (*print-lines* 3))
  116.   (pprint '(progn (setq a 1 b 2 c 3 d 4))))
  117. (PROGN (SETQ A 1
  118.              B 2
  119.              C 3 ..))
  120.  
  121. (The symbol ``..'' is printed out to ensure that a reader error will occur if
  122. the output is later read. A symbol different from ``...'' is used to indicate
  123. that a different kind of abbreviation has occurred.)
  124. [change_end]
  125.  
  126. -------------------------------------------------------------------------------
  127.  
  128. 27.3. Dynamic Control of the Arrangement of Output
  129.  
  130. [change_begin]
  131. The following functions and macros support precise control of what should be
  132. done when a piece of output is too large to fit in the space available. Three
  133. concepts underlie the way these operations work: logical blocks, conditional
  134. newlines, and sections. Before proceeding further, it is important to define
  135. these terms.
  136.  
  137. The first line of figure 27-1 shows a schematic piece of output. The characters
  138. in the output are represented by hyphens. The positions of conditional newlines
  139. are indicated by digits. The beginnings and ends of logical blocks are
  140. indicated in the figure by ``<'' and ``>'' respectively.
  141.  
  142. The output as a whole is a logical block and the outermost section. This
  143. section is indicated by the 0's on the second line of figure 27-1. Logical
  144. blocks nested within the output are specified by the macro
  145. pprint-logical-block. Conditional newline positions are specified by calls on
  146. pprint-newline. Each conditional newline defines two sections (one before it
  147. and one after it) and is associated with a third (the section immediately
  148. containing it).
  149.  
  150. The section after a conditional newline consists of all the output up to, but
  151. not including, (a) the next conditional newline immediately contained in the
  152. same logical block; or if (a) is not applicable, (b) the next newline that is
  153. at a lesser level of nesting in logical blocks; or if (b) is not applicable,
  154. (c) the end of the output.
  155.  
  156. The section before a conditional newline consists of all the output back to,
  157. but not including, (a) the previous conditional newline that is immediately
  158. contained in the same logical block; or if (a) is not applicable, (b) the
  159. beginning of the immediately containing logical block. The last four lines in
  160. figure 27-1 indicate the sections before and after the four conditional
  161. newlines.
  162.  
  163. The section immediately containing a conditional newline is the shortest
  164. section that contains the conditional newline in question. In figure 27-1, the
  165. first conditional newline is immediately contained in the section marked with
  166. 0's, the second and third conditional newlines are immediately contained in the
  167. section before the fourth conditional newline, and the fourth conditional
  168. newline is immediately contained in the section after the first conditional
  169. newline.
  170.  
  171.  
  172. ----------------------------------------------------------------
  173. Figure 27-1: Example of Logical Blocks, Conditional Newlines, and Sections
  174.  
  175.                  <-1---<--<--2---3->--4-->->
  176.                  000000000000000000000000000
  177.                  11 111111111111111111111111
  178.                            22 222
  179.                               333 3333
  180.                         44444444444444 44444
  181.  
  182. ----------------------------------------------------------------
  183.  
  184. Whenever possible, the pretty printer displays the entire contents of a section
  185. on a single line. However, if the section is too long to fit in the space
  186. available, line breaks are inserted at conditional newline positions within the
  187. section.
  188.  
  189. [Function]
  190. pprint-newline kind &optional stream
  191.  
  192. The stream (which defaults to *standard-output*) follows the standard
  193. conventions for stream arguments to printing functions (that is, nil stands for
  194. *standard-output* and t stands for *terminal-io*). The kind argument specifies
  195. the style of conditional newline. It must be one of :linear, :fill, :miser, or
  196. :mandatory. An error is signaled if any other value is supplied. If stream is a
  197. pretty printing stream created by pprint-logical-block, a line break is
  198. inserted in the output when the appropriate condition below is satisfied.
  199. Otherwise, pprint-newline has no effect. The value nil is always returned.
  200.  
  201. If kind is :linear, it specifies a `linear-style' conditional newline. A line
  202. break is inserted if and only if the immediately containing section cannot be
  203. printed on one line. The effect of this is that line breaks are either inserted
  204. at every linear-style conditional newline in a logical block or at none of
  205. them.
  206.  
  207. If kind is :miser, it specifies a `miser-style' conditional newline. A line
  208. break is inserted if and only if the immediately containing section cannot be
  209. printed on one line and miser style is in effect in the immediately containing
  210. logical block. The effect of this is that miser-style conditional newlines act
  211. like linear-style conditional newlines, but only when miser style is in effect.
  212. Miser style is in effect for a logical block if and only if the starting
  213. position of the logical block is less than or equal to *print-miser-width* from
  214. the right margin.
  215.  
  216. If kind is :fill, it specifies a `fill-style' conditional newline. A line break
  217. is inserted if and only if either (a) the following section cannot be printed
  218. on the end of the current line, (b) the preceding section was not printed on a
  219. single line, or (c) the immediately containing section cannot be printed on one
  220. line and miser style is in effect in the immediately containing logical block.
  221. If a logical block is broken up into a number of subsections by fill-style
  222. conditional newlines, the basic effect is that the logical block is printed
  223. with as many subsections as possible on each line. However, if miser style is
  224. in effect, fill-style conditional newlines act like linear-style conditional
  225. newlines.
  226.  
  227. If kind is :mandatory, it specifies a `mandatory-style' conditional newline. A
  228. line break is always inserted. This implies that none of the containing
  229. sections can be printed on a single line and will therefore trigger the
  230. insertion of line breaks at linear-style conditional newlines in these
  231. sections.
  232.  
  233. When a line break is inserted by any type of conditional newline, any blanks
  234. that immediately precede the conditional newline are omitted from the output
  235. and indentation is introduced at the beginning of the next line. By default,
  236. the indentation causes the following line to begin in the same horizontal
  237. position as the first character in the immediately containing logical block.
  238. (The indentation can be changed via pprint-indent.)
  239.  
  240. There are a variety of ways unconditional newlines can be introduced into the
  241. output (for example, via terpri or by printing a string containing a newline
  242. character). As with mandatory conditional newlines, this prevents any of the
  243. containing sections from being printed on one line. In general, when an
  244. unconditional newline is encountered, it is printed out without suppression of
  245. the preceding blanks and without any indentation following it. However, if a
  246. per-line prefix has been specified (see pprint-logical-block), that prefix will
  247. always be printed no matter how a newline originates.
  248.  
  249. [Macro]
  250.  
  251. pprint-logical-block (stream-symbol list
  252.        [[ { :prefix | :per-line-prefix} p | :suffix s ]])
  253.        {form}*
  254.  
  255. This macro causes printing to be grouped into a logical block. It returns nil.
  256.  
  257. The stream-symbol must be a symbol. If it is nil, it is treated the same as if
  258. it were *standard-output*. If it is t, it is treated the same as if it were
  259. *terminal-io*. The run-time value of stream-symbol must be a stream (or nil
  260. standing for *standard-output* or t standing for *terminal-io*). The logical
  261. block is printed into this destination stream.
  262.  
  263. The body (which consists of the forms) can contain any arbitrary Lisp forms.
  264. Within the body, stream-symbol (or *standard-output* if stream-symbol is nil,
  265. or *terminal-io* if stream-symbol is t) is bound to a ``pretty printing''
  266. stream that supports decisions about the arrangement of output and then
  267. forwards the output to the destination stream. All the standard printing
  268. functions (for example, write, princ, terpri) can be used to send output to the
  269. pretty printing stream created by pprint-logical-block. All and only the output
  270. sent to this pretty printing stream is treated as being in the logical block.
  271.  
  272. pprint-logical-block and the pretty printing stream it creates have dynamic
  273. extent. It is undefined what happens if output is attempted outside of this
  274. extent to the pretty printing stream created. It is unspecified what happens
  275. if, within this extent, any output is sent directly to the underlying
  276. destination stream (by calling write-char, for example).
  277.  
  278. The :suffix, :prefix, and :per-line-prefix arguments must all be expressions
  279. that (at run time) evaluate to strings. The :suffix argument s (which defaults
  280. to the null string) specifies a suffix that is printed just after the logical
  281. block. The :prefix and :per-line-prefix arguments are mutually exclusive. If
  282. neither :prefix nor :per-line-prefix is specified, a :prefix of the null string
  283. is assumed. The :prefix argument specifies a prefix p that is printed before
  284. the beginning of the logical block. The :per-line-prefix specifies a prefix p
  285. that is printed before the block and at the beginning of each subsequent line
  286. in the block. An error is signaled if :prefix and :per-line-prefix are both
  287. used or if a :suffix, :prefix, or :pre-line-prefix argument does not evaluate
  288. to a string.
  289.  
  290. The list is interpreted as being a list that the body is responsible for
  291. printing. (See pprint-exit-if-list-exhausted and pprint-pop.) If list does not
  292. (at run time) evaluate to a list, it is printed using write. (This makes it
  293. easier to write printing functions that are robust in the face of malformed
  294. arguments.) If *print-circle* (and possibly also *print-shared*) is not nil and
  295. list is a circular (or shared) reference to a cons, then an appropriate ``#n#''
  296. marker is printed. (This makes it easy to write printing functions that provide
  297. full support for circularity and sharing abbreviation.) If *print-level* is not
  298. nil and the logical block is at a dynamic nesting depth of greater than
  299. *print-level* in logical blocks, ``#'' is printed. (This makes it easy to write
  300. printing functions that provide full support for depth abbreviation.)
  301.  
  302. If any of the three preceding conditions occurs, the indicated output is
  303. printed on stream-symbol and the body is skipped along with the printing of the
  304. prefix and suffix. (If the body is not responsible for printing a list, then
  305. the first two tests above can be turned off by supplying nil for the list
  306. argument.)
  307.  
  308. In addition to the list argument of pprint-logical-block, the arguments of the
  309. standard printing functions such as write, print, pprint, print1, and pprint,
  310. as well as the arguments of the standard format directives such as ~A, ~S, (and
  311. ~W) are all checked (when necessary) for circularity and sharing. However, such
  312. checking is not applied to the arguments of the functions write-line,
  313. write-string, and write-char or to the literal text output by format. A
  314. consequence of this is that you must use one of the latter functions if you
  315. want to print some literal text in the output that is not supposed to be
  316. checked for circularity or sharing. (See the examples below.)
  317.  
  318. -------------------------------------------------------------------------------
  319. Implementation note: Detection of circularity and sharing is supported by the
  320. pretty printer by in essence performing the requested output twice. On the
  321. first pass, circularities and sharing are detected and the actual outputting of
  322. characters is suppressed. On the second pass, the appropriate ``#n='' and
  323. ``#n#'' markers are inserted and characters are output.
  324.  
  325. A consequence of this two-pass approach to the detection of circularity and
  326. sharing is that the body of a pprint-logical-block must not perform any
  327. side-effects on the surrounding environment. This includes not modifying any
  328. variables that are bound outside of its scope. Obeying this restriction is
  329. facilitated by using pprint-pop, instead of an ordinary pop when traversing a
  330. list being printed by the body of a pprint-logical-block.)
  331. -------------------------------------------------------------------------------
  332.  
  333. [Macro]
  334. pprint-exit-if-list-exhausted
  335.  
  336. pprint-exit-if-list-exhausted tests whether or not the list argument of
  337. pprint-logical-block has been exhausted (see pprint-pop). If this list has been
  338. reduced to nil, pprint-exit-if-list-exhausted terminates the execution of the
  339. immediately containing pprint-logical-block except for the printing of the
  340. suffix. Otherwise pprint-exit-if-list-exhausted returns nil. An error message
  341. is issued if pprint-exit-if-list-exhausted is used anywhere other than
  342. syntactically nested within a call on pprint-logical-block. It is undefined
  343. what happens if pprint-pop is executed outside of the dynamic extent of this
  344. pprint-logical-block.
  345.  
  346. [Macro]
  347. pprint-pop
  348.  
  349. pprint-pop pops elements one at a time off the list argument of
  350. pprint-logical-block, taking care to obey *print-length*, *print-circle*, and
  351. *print-shared*. An error message is issued if it is used anywhere other than
  352. syntactically nested within a call on pprint-logical-block. It is undefined
  353. what happens if pprint-pop is executed outside of the dynamic extent of this
  354. call on pprint-logical-block.
  355.  
  356. Each time pprint-pop is called, it pops the next value off the list argument of
  357. pprint-logical-block and returns it. However, before doing this, it performs
  358. three tests. If the remaining list is not a list (neither a cons nor nil), ``.
  359. '' is printed followed by the remaining list. (This makes it easier to write
  360. printing functions that are robust in the face of malformed arguments.) If
  361. *print-length* is nil and pprint-pop has already been called *print-length*
  362. times within the immediately containing logical block, ``...'' is printed.
  363. (This makes it easy to write printing functions that properly handle
  364. *print-length*.) If *print-circle* (and possibly also *print-shared*) is not
  365. nil, and the remaining list is a circular (or shared) reference, then ``. '' is
  366. printed followed by an appropriate ``#n#'' marker. (This catches instances of
  367. cdr circularity and sharing in lists.)
  368.  
  369. If any of the three preceding conditions occurs, the indicated output is
  370. printed on the pretty printing stream created by the immediately containing
  371. pprint-logical-block and the execution of the immediately containing
  372. pprint-logical-block is terminated except for the printing of the suffix.
  373.  
  374. If pprint-logical-block is given a list argument of nil-because it is not
  375. processing a list-pprint-pop can still be used to obtain support for
  376. *print-length* (see the example function pprint-vector below). In this
  377. situation, the first and third tests above are disabled and pprint-pop always
  378. returns nil.
  379.  
  380. [Function]
  381. pprint-indent relative-to n &optional stream
  382.  
  383. pprint-indent specifies the indentation to use in a logical block. Stream
  384. (which defaults to *standard-output*) follows the standard conventions for
  385. stream arguments to printing functions. The argument n specifies the
  386. indentation in ems. If relative-to is :block, the indentation is set to the
  387. horizontal position of the first character in the block plus n ems. If
  388. relative-to is :current, the indentation is set to the current output position
  389. plus n ems.
  390.  
  391. The argument n can be negative; however, the total indentation cannot be moved
  392. left of the beginning of the line or left of the end of the rightmost per-line
  393. prefix. Changes in indentation caused by pprint-indent do not take effect until
  394. after the next line break. In addition, in miser mode all calls on
  395. pprint-indent are ignored, forcing the lines corresponding to the logical block
  396. to line up under the first character in the block.
  397.  
  398. An error is signaled if a value other than :block or :current is supplied for
  399. relative-to. If stream is a pretty printing stream created by
  400. pprint-logical-block, pprint-indent sets the indentation in the innermost
  401. dynamically enclosing logical block. Otherwise, pprint-indent has no effect.
  402. The value nil is always returned.
  403.  
  404. [Function]
  405. pprint-tab kind colnum colinc &optional stream
  406.  
  407. pprint-tab specifies tabbing as performed by the standard format directive ~T.
  408. Stream (which defaults to *standard-output*) follows the standard conventions
  409. for stream arguments to printing functions. The arguments colnum and colinc
  410. correspond to the two parameters to ~T and are in terms of ems. The kind
  411. argument specifies the style of tabbing. It must be one of :line (tab as by ~T)
  412. :section (tab as by ~T, but measuring horizontal positions relative to the
  413. start of the dynamically enclosing section), :line-relative (tab as by ~@T), or
  414. :section-relative (tab as by ~@T, but measuring horizontal positions relative
  415. to the start of the dynamically enclosing section). An error is signaled if any
  416. other value is supplied for kind. If stream is a pretty printing stream created
  417. by pprint-logical-block, tabbing is performed. Otherwise, pprint-tab has no
  418. effect. The value nil is always returned.
  419.  
  420. [Function]
  421. pprint-fill stream list &optional colon? atsign?
  422. pprint-linear stream list &optional colon? atsign?
  423. pprint-tabular stream list &optional colon? atsign? tabsize
  424.  
  425. These three functions specify particular ways of pretty printing lists. Stream
  426. follows the standard conventions for stream arguments to printing functions.
  427. Each function prints parentheses around the output if and only if colon?
  428. (default t) is not nil. Each function ignores its atsign? argument and returns
  429. nil. (These two arguments are included in this way so that these functions can
  430. be used via ~/.../ and as set-pprint-dispatch functions as well as directly.)
  431. Each function handles abbreviation and the detection of circularity and sharing
  432. correctly and uses write to print list when given a non-list argument.
  433.  
  434. The function pprint-linear prints a list either all on one line or with each
  435. element on a separate line. The function pprint-fill prints a list with as many
  436. elements as possible on each line. The function pprint-tabular is the same as
  437. pprint-fill except that it prints the elements so that they line up in columns.
  438. This function takes an additional argument tabsize (default 16) that specifies
  439. the column spacing in ems.
  440.  
  441. As an example of the interaction of logical blocks, conditional newlines, and
  442. indentation, consider the function pprint-defun below. This function pretty
  443. prints a list whose car is defun in the standard way assuming that the length
  444. of the list is exactly 4.
  445.  
  446. ;;; Pretty printer function for DEFUN forms.
  447.  
  448. (defun pprint-defun (list)
  449.   (pprint-logical-block (nil list :prefix "(" :suffix ")")
  450.     (write (first list))
  451.     (write-char #¥space)
  452.     (pprint-newline :miser)
  453.     (pprint-indent :current 0)
  454.     (write (second list))
  455.     (write-char #¥space)
  456.     (pprint-newline :fill)
  457.     (write (third list))
  458.     (pprint-indent :block 1)
  459.     (write-char #¥space)
  460.     (pprint-newline :linear)
  461.     (write (fourth list))))
  462.  
  463. Suppose that one evaluates the following:
  464.  
  465. (pprint-defun '(defun prod (x y) (* x y)))
  466.  
  467. If the line width available is greater than or equal to 26, all of the output
  468. appears on one line. If the width is reduced to 25, a line break is inserted at
  469. the linear-style conditional newline before (* X Y), producing the output shown
  470. below. The (pprint-indent :block 1) causes (* X Y) to be printed at a relative
  471. indentation of 1 in the logical block.
  472.  
  473. (DEFUN PROD (X Y)
  474.   (* X Y))
  475.  
  476. If the width is 15, a line break is also inserted at the fill-style conditional
  477. newline before the argument list. The argument list lines up under the function
  478. name because of the call on (pprint-indent :current 0) before the printing of
  479. the function name.
  480.  
  481. (DEFUN PROD
  482.        (X Y)
  483.   (* X Y))
  484.  
  485. If *print-miser-width* were greater than or equal to 14, the output would have
  486. been entirely in miser mode. All indentation changes are ignored in miser mode
  487. and line breaks are inserted at miser-style conditional newlines. The result
  488. would have been as follows:
  489.  
  490. (DEFUN
  491.  PROD
  492.  (X Y)
  493.  (* X Y))
  494.  
  495. As an example of the use of a per-line prefix, consider that evaluating the
  496. expression
  497.  
  498. (pprint-logical-block (nil nil :per-line-prefix ";;; ")
  499.   (pprint-defun '(defun prod (x y) (* x y))))
  500.  
  501. produces the output
  502.  
  503. ;;; (DEFUN PROD
  504. ;;;        (X Y)
  505. ;;;   (* X Y))
  506.  
  507. with a line width of 20 and nil as the value of the printer control variable
  508. *print-miser-width*.
  509.  
  510. (If *print-miser-width* were not nil the output
  511.  
  512. ;;; (DEFUN
  513. ;;;  PROD
  514. ;;;  (X Y)
  515. ;;;  (* X Y))
  516.  
  517. might appear instead.)
  518.  
  519. As a more complex (and realistic) example, consider the function pprint-let
  520. below. This specifies how to pretty print a let in the standard style. It is
  521. more complex than pprint-defun because it has to deal with nested structure.
  522. Also, unlike pprint-defun, it contains complete code to print readably any
  523. possible list that begins with the symbol let. The outermost
  524. pprint-logical-block handles the printing of the input list as a whole and
  525. specifies that parentheses should be printed in the output. The second
  526. pprint-logical-block handles the list of binding pairs. Each pair in the list
  527. is itself printed by the innermost pprint-logical-block. (A loop is used
  528. instead of merely decomposing the pair into two elements so that readable
  529. output will be produced no matter whether the list corresponding to the pair
  530. has one element, two elements, or (being malformed) has more than two
  531. elements.) A space and a fill-style conditional newline are placed after each
  532. pair except the last. The loop at the end of the topmost pprint-logical-block
  533. prints out the forms in the body of the let separated by spaces and
  534. linear-style conditional newlines.
  535.  
  536. ;;; Pretty printer function for LET forms,
  537. ;;; carefully coded to handle malformed binding pairs.
  538.  
  539. (defun pprint-let (list)
  540.   (pprint-logical-block (nil list :prefix "(" :suffix ")")
  541.     (write (pprint-pop))
  542.     (pprint-exit-if-list-exhausted)
  543.     (write-char #¥space)
  544.     (pprint-logical-block
  545.         (nil (pprint-pop) :prefix "(" :suffix ")")
  546.       (pprint-exit-if-list-exhausted)
  547.       (loop (pprint-logical-block
  548.                 (nil (pprint-pop) :prefix "(" :suffix ")")
  549.               (pprint-exit-if-list-exhausted)
  550.               (loop (write (pprint-pop))
  551.                     (pprint-exit-if-list-exhausted)
  552.                     (write-char #¥space)
  553.                     (pprint-newline :linear)))
  554.             (pprint-exit-if-list-exhausted)
  555.             (write-char #¥space)
  556.             (pprint-newline :fill)))
  557.     (pprint-indent :block 1)
  558.     (loop (pprint-exit-if-list-exhausted)
  559.           (write-char #¥space)
  560.           (pprint-newline :linear)
  561.           (write (pprint-pop)))))
  562.  
  563. Suppose that the following is evaluated with *print-level* having the value 4
  564. and *print-circle* having the value t.
  565.  
  566. (pprint-let '#1=(let (x (*print-length* (f (g 3)))
  567.                       (z . 2) (k (car y)))
  568.                   (setq x (sqrt z)) #1#))
  569.  
  570. If the line length is greater than or equal to 77, the output produced appears
  571. on one line. However, if the line length is 76, line breaks are inserted at the
  572. linear-style conditional newlines separating the forms in the body and the
  573. output below is produced. Note that the degenerate binding pair X is printed
  574. readably even though it fails to be a list; a depth abbreviation marker is
  575. printed in place of (G 3); the binding pair (Z . 2) is printed readably even
  576. though it is not a proper list; and appropriate circularity markers are
  577. printed.
  578.  
  579. #1=(LET (X (*PRINT-LENGTH* (F #)) (Z . 2) (K (CAR Y)))
  580.      (SETQ X (SQRT Z))
  581.      #1#)
  582.  
  583. If the line length is reduced to 35, a line break is inserted at one of the
  584. fill-style conditional newlines separating the binding pairs.
  585.  
  586. #1=(LET (X (*PRINT-PRETTY* (F #))
  587.          (Z . 2) (K (CAR Y)))
  588.      (SETQ X (SQRT Z))
  589.      #1#)
  590.  
  591. Suppose that the line length is further reduced to 22 and *print-length* is set
  592. to 3. In this situation, line breaks are inserted after both the first and
  593. second binding pairs. In addition, the second binding pair is itself broken
  594. across two lines. Clause (b) of the description of fill-style conditional
  595. newlines prevents the binding pair (Z . 2) from being printed at the end of the
  596. third line. Note that the length abbreviation hides the circularity from view
  597. and therefore the printing of circularity markers disappears.
  598.  
  599. (LET (X
  600.       (*PRINT-LENGTH*
  601.        (F #))
  602.       (Z . 2) ...)
  603.   (SETQ X (SQRT Z))
  604.   ...)
  605.  
  606. The function pprint-tabular could be defined as follows:
  607.  
  608. (defun pprint-tabular (s list &optional (c? t) a? (size 16))
  609.   (declare (ignore a?))
  610.   (pprint-logical-block
  611.       (s list :prefix (if c? "(" "") :suffix (if c? ")" ""))
  612.     (pprint-exit-if-list-exhausted)
  613.     (loop (write (pprint-pop) :stream s)
  614.           (pprint-exit-if-list-exhausted)
  615.           (write-char #¥space s)
  616.           (pprint-tab :section-relative 0 size s)
  617.           (pprint-newline :fill s))))
  618.  
  619. Evaluating the following with a line length of 25 produces the output shown.
  620.  
  621. (princ "Roads ")
  622. (pprint-tabular nil '(elm main maple center) nil nil 8)
  623. Roads ELM     MAIN
  624.       MAPLE   CENTER
  625.  
  626. The function below prints a vector using #(...) notation.
  627.  
  628. (defun pprint-vector (v)
  629.   (pprint-logical-block (nil nil :prefix "#(" :suffix ")")
  630.     (let ((end (length v)) (i 0))
  631.       (when (plusp end)
  632.         (loop (pprint-pop)
  633.               (write (aref v i))
  634.               (if (= (incf i) end) (return nil))
  635.               (write-char #¥space)
  636.               (pprint-newline :fill))))))
  637.  
  638. Evaluating the following with a line length of 15 produces the output shown.
  639.  
  640. (pprint-vector '#(12 34 567 8 9012 34 567 89 0 1 23))
  641.  
  642. #(12 34 567 8
  643.   9012 34 567
  644.   89 0 1 23)
  645.  
  646. [change_end]
  647.  
  648. -------------------------------------------------------------------------------
  649.  
  650. 27.4. Format Directive Interface
  651.  
  652. [change_begin]
  653. The primary interface to operations for dynamically determining the arrangement
  654. of output is provided through the functions above. However, an additional
  655. interface is provided via a set of format directives because, as shown by the
  656. examples in this section and the next, format strings are typically a much more
  657. compact way to specify pretty printing. In addition, without such an interface,
  658. one would have to abandon the use of format when interacting with the pretty
  659. printer.
  660.  
  661. ~W   Write. An arg, any Lisp object, is printed obeying every printer control
  662.      variable (as by write). In addition, ~W interacts correctly with depth
  663.      abbreviation by not resetting the depth counter to zero. ~W does not
  664.      accept parameters. If given the colon modifier, ~W binds *print-pretty* to
  665.      t. If given the atsign modifier, ~W binds *print-level* and *print-length*
  666.      to nil.
  667.  
  668.      ~W provides automatic support for circularity detection. If *print-circle*
  669.      (and possibly also *print-shared*) is not nil and ~W is applied to an
  670.      argument that is a circular (or shared) reference, an appropriate ``#n#''
  671.      marker is inserted in the output instead of printing the argument.
  672.  
  673. ~_   Conditional newline. Without any modifiers, ~_ is equivalent to
  674.      (pprint-newline :linear). The directive ~@_ is equivalent to
  675.      (pprint-newline :miser). The directive ~:_ is equivalent to
  676.      (pprint-newline :fill). The directive ~:@_ is equivalent to
  677.      (pprint-newline :mandatory).
  678.  
  679. ~<str~:>
  680.      Logical block. If ~:> is used to terminate a ~<... directive, the
  681.      directive is equivalent to a call on pprint-logical-block. The format
  682.      argument corresponding to the ~<...~:> directive is treated in the same
  683.      way as the list argument to pprint-logical-block, thereby providing
  684.      automatic support for non-list arguments and the detection of circularity,
  685.      sharing, and depth abbreviation. The portion of the format control string
  686.      nested within the ~<...~:> specifies the :prefix (or :per-line-prefix),
  687.      :suffix, and body of the pprint-logical-block.
  688.  
  689.      The format string portion enclosed by ~<...~:> can be divided into
  690.      segments ~<prefix~;body~;suffix~:> by ~; directives. If the first section
  691.      is terminated by ~@;, it specifies a per-line prefix rather than a simple
  692.      prefix. The prefix and suffix cannot contain format directives. An error
  693.      is signaled if either the prefix or suffix fails to be a constant string
  694.      or if the enclosed portion is divided into more than three segments.
  695.  
  696.      If the enclosed portion is divided into only two segments, the suffix
  697.      defaults to the null string. If the enclosed portion consists of only a
  698.      single segment, both the prefix and the suffix default to the null string.
  699.      If the colon modifier is used (that is, ~:<...~:>), the prefix and suffix
  700.      default to "(" and ")", respectively, instead of the null string.
  701.  
  702.      The body segment can be any arbitrary format control string. This format
  703.      control string is applied to the elements of the list corresponding to the
  704.      ~<...~:> directive as a whole. Elements are extracted from this list using
  705.      pprint-pop, thereby providing automatic support for malformed lists and
  706.      the detection of circularity, sharing, and length abbreviation. Within the
  707.      body segment, ~^ acts like pprint-exit-if-list-exhausted.
  708.  
  709.      ~<...~:> supports a feature not supported by pprint-logical-block. If ~:@>
  710.      is used to terminate the directive (that is, ~<...~:@>), then a fill-style
  711.      conditional newline is automatically inserted after each group of blanks
  712.      immediately contained in the body (except for blanks after a ~<newline>
  713.      directive). This makes it easy to achieve the equivalent of paragraph
  714.      filling.
  715.  
  716.      If the atsign modifier is used with ~<...~:>, the entire remaining
  717.      argument list is passed to the directive as its argument. All of the
  718.      remaining arguments are always consumed by ~@<...~:>, even if they are not
  719.      all used by the format string nested in the directive. Other than the
  720.      difference in its argument, ~@<...~:> is exactly the same as ~<...~:>,
  721.      except that circularity (and sharing) detection is not applied if the
  722.      ~@<...~:> is at top level in a format string. This ensures that
  723.      circularity detection is applied only to data lists and not to format
  724.      argument lists.
  725.  
  726.      To a considerable extent, the basic form of the directive ~<...~> is
  727.      incompatible with the dynamic control of the arrangement of output by ~W,
  728.      ~_, ~<...~:>, ~I, and ~:T. As a result, an error is signaled if any of
  729.      these directives is nested within ~<...~>. Beyond this, an error is also
  730.      signaled if the ~<...~:;...~> form of ~<...~> is used in the same format
  731.      string with ~W, ~_, ~<...~:>, ~I, or ~:T.
  732.  
  733. ~I   Indent. ~nI is equivalent to (pprint-indent :block n). ~:nI is equivalent
  734.      to (pprint-indent :current n). In both cases, n defaults to zero if it is
  735.      omitted.
  736.  
  737. ~:T  Tabulate. If the colon modifier is used with the ~T directive, the tabbing
  738.      computation is done relative to the column where the section immediately
  739.      containing the directive begins, rather than with respect to column zero.
  740.      ~n,m:T is equivalent to (pprint-tab :section n m). ~n,m:@T is equivalent
  741.      to (pprint-tab :section-relative n m). The numerical parameters are both
  742.      interpreted as being in units of ems and both default to 1.
  743.  
  744. ~/name/
  745.      Call function. User-defined functions can be called from within a format
  746.      string by using the directive ~/name/. The colon modifier, the atsign
  747.      modifier, and arbitrarily many parameters can be specified with the
  748.      ~/name/ directive. The name can be any string that does not contain ``/''.
  749.      All of the characters in name are treated as if they were upper case. If
  750.      name contains a ``:'' or ``::'', then everything up to but not including
  751.      the first ``:'' or ``::'' is taken to be a string that names a package.
  752.      Everything after the first ``:'' or ``::'' (if any) is taken to be a
  753.      string that names a symbol. The function corresponding to a ~/name/
  754.      directive is obtained by looking up the symbol that has the indicated name
  755.      in the indicated package. If name does not contain a ``:'' or ``::'', then
  756.      the whole name string is looked up in the user package.
  757.  
  758.      When a ~/name/ directive is encountered, the indicated function is called
  759.      with four or more arguments. The first four arguments are the output
  760.      stream, the format argument corresponding to the directive, the value t if
  761.      the colon modifier was used (nil otherwise), and the value t if the atsign
  762.      modifier was used (nil otherwise). The remaining arguments consist of any
  763.      parameters specified with the directive. The function should print the
  764.      argument appropriately. Any values returned by the function are ignored.
  765.  
  766.      The three functions pprint-linear, pprint-fill, and pprint-tabular are
  767.      designed so that they can be called by ~/.../ (that is, ~/pprint-linear/,
  768.      ~/pprint-fill/, and ~/pprint-tabular/. In particular they take colon and
  769.      atsign arguments.
  770.  
  771. As examples of the convenience of specifying pretty printing with format
  772. strings, consider the functions pprint-defun and pprint-let used as examples in
  773. the last section. They can be more compactly defined as follows. The function
  774. pprint-vector cannot be defined using format, because the data structure it
  775. traverses is not a list. The function pprint-tabular is inconvenient to define
  776. using format, because of the need to pass its tabsize argument through to a ~:T
  777. directive nested within an iteration over a list.
  778.  
  779. (defun pprint-defun (list)
  780.   (format t
  781. "~:<~W ~@_~:I~W ~:_~W~1I ~_~W~:>"
  782. list))
  783.  
  784. (defun pprint-let (list)
  785.   (format t "~:<~W~^ ~:<~@{~:<~@{~W~^ ~_~}~:>~^ ~:_~}~:>~1I~
  786.                 ~@{~^ ~_~W~}~:>"
  787.           list))
  788.  
  789. [change_end]
  790.  
  791. -------------------------------------------------------------------------------
  792.  
  793. 27.5. Compiling Format Control Strings
  794.  
  795. [change_begin]
  796. The control strings used by format are essentially programs that perform
  797. printing. The macro formatter provides the efficiency of using a compiled
  798. function for printing without losing the visual compactness of format strings.
  799.  
  800. [Macro]
  801. formatter control-string
  802.  
  803. The control-string must be a literal string. An error is signaled if
  804. control-string is not a valid format control string. The macro formatter
  805. expands into an expression of the form (function (lambda (stream &rest args)
  806. ...)) that does the printing specified by control-string. The lambda created
  807. accepts an output stream as its first argument and zero or more data values as
  808. its remaining arguments. The value returned by the lambda is the tail (if any)
  809. of the data values that are not printed out by control-string. (For example, if
  810. the control-string is "~A~A", the cddr (if any) of the data values is
  811. returned.) The form (formatter "~%~2@{~S, ~}") is equivalent to the following:
  812.  
  813. #'(lambda (stream &rest args)
  814.     (terpri stream)
  815.     (dotimes (n 2)
  816.       (if (null args) (return nil))
  817.       (prin1 (pop args) stream)
  818.       (write-string ", " stream))
  819.     args)
  820.  
  821. In support of the above mechanism, format is extended so that it accepts
  822. functions as its second argument as well as strings. When a function is
  823. provided, it must be a function of the form created by formatter. The function
  824. is called with the appropriate output stream as its first argument and the data
  825. arguments to format as its remaining arguments. The function should perform
  826. whatever output is necessary and return the unused tail of the arguments (if
  827. any). The directives and ~{~} with no body are also extended so that they
  828. accept functions as well as control strings. Every other standard function that
  829. takes a format string as an argument (for example, error and warn) is also
  830. extended so that it can accept functions of the form above instead.
  831. [change_end]
  832.  
  833. -------------------------------------------------------------------------------
  834.  
  835. 27.6. Pretty Printing Dispatch Tables
  836.  
  837. [change_begin]
  838. When *print-pretty* is not nil, the pprint dispatch table in the variable
  839. *print-pprint-dispatch* controls how objects are printed. The information in
  840. this table takes precedence over all other mechanisms for specifying how to
  841. print objects. In particular, it overrides user-defined print-object methods
  842. and print functions for structures. However, if there is no specification for
  843. how to pretty print a particular kind of object, it is then printed using the
  844. standard mechanisms as if *print-pretty* were nil.
  845.  
  846. A pprint dispatch table is a mapping from keys to pairs of values. The keys are
  847. type specifiers. The values are functions and numerical priorities. Basic
  848. insertion and retrieval is done based on the keys with the equality of keys
  849. being tested by equal. The function to use when pretty printing an object is
  850. chosen by finding the highest priority function in *print-pprint-dispatch* that
  851. is associated with a type specifier that matches the object.
  852.  
  853. [Function]
  854. copy-pprint-dispatch &optional table
  855.  
  856. A copy is made of table, which defaults to the current pprint dispatch table.
  857. If table is nil, a copy is returned of the initial value of
  858. *print-pprint-dispatch*.
  859.  
  860. [Function]
  861. pprint-dispatch object &optional table
  862.  
  863. This retrieves the highest priority function from a pprint table that is
  864. associated with a type specifier in the table that matches object. The function
  865. is chosen by finding all the type specifiers in table that match the object and
  866. selecting the highest priority function associated with any of these type
  867. specifiers. If there is more than one highest priority function, an arbitrary
  868. choice is made. If no type specifiers match the object, a function is returned
  869. that prints object with *print-pretty* bound to nil.
  870.  
  871. As a second return value, pprint-dispatch returns a flag that is t if a
  872. matching type specifier was found in table and nil if not.
  873.  
  874. Table (which defaults to *print-pprint-dispatch*) must be a pprint dispatch
  875. table. Table can be nil, in which case retrieval is done in the initial value
  876. of *print-pprint-dispatch*.
  877.  
  878. When *print-pretty* is t, (write object :stream s) is equivalent to (funcall
  879. (pprint-dispatch object) s object).
  880.  
  881. [Function]
  882. set-pprint-dispatch type function &optional priority table
  883.  
  884. This puts an entry into a pprint dispatch table and returns nil. The type must
  885. be a valid type specifier and is the key of the entry. The first action of
  886. set-pprint-dispatch is to remove any pre-existing entry associated with type.
  887. This guarantees that there will never be two entries associated with the same
  888. type specifier in a given pprint dispatch table. Equality of type specifiers is
  889. tested by equal.
  890.  
  891. Two values are associated with each type specifier in a pprint dispatch table:
  892. a function and a priority. The function must accept two arguments: the stream
  893. to send output to and the object to be printed. The function should pretty
  894. print the object on the stream. The function can assume that object satisfies
  895. type. The function should obey *print-readably*. Any values returned by the
  896. function are ignored.
  897.  
  898. The priority (which defaults to 0) must be a non-complex number. This number is
  899. used as a priority to resolve conflicts when an object matches more than one
  900. entry. An error is signaled if priority fails to be a non-complex number.
  901.  
  902. The table (which defaults to the value of *print-pprint-dispatch*) must be a
  903. pprint dispatch table. The specified entry is placed in this table.
  904.  
  905. It is permissible for function to be nil. In this situation, there will be no
  906. type entry in table after set-pprint-dispatch is evaluated.
  907.  
  908. To facilitate the use of pprint dispatch tables for controlling the pretty
  909. printing of Lisp code, the type-specifier argument of the function
  910. set-pprint-dispatch is allowed to contain the form (cons car-type cdr-type).
  911. This form indicates that the corresponding object must be a cons whose car
  912. satisfies the type specifier car-type and whose cdr satisfies the type
  913. specifier cdr-type. The cdr-type can be omitted, in which case it defaults to
  914. t.
  915.  
  916. The initial value of *print-pprint-dispatch* is implementation-dependent.
  917. However, the initial entries all use a special class of priorities that are
  918. less than every priority that can be specified using set-pprint-dispatch. This
  919. guarantees that pretty printing functions specified by users will override
  920. everything in the initial value of *print-pprint-dispatch*.
  921.  
  922. Consider the following examples. The first form restores
  923. *print-pprint-dispatch* to its initial value. The next two forms then specify a
  924. special way of pretty printing ratios. Note that the more specific type
  925. specifier has to be associated with a higher priority.
  926.  
  927. (setq *print-pprint-dispatch*
  928.       (copy-pprint-dispatch nil))
  929.  
  930. (defun div-print (s r colon? atsign?)
  931.   (declare (ignore colon? atsign?))
  932.   (format s "(/ ~D ~D)" (numerator (abs r)) (denominator r)))
  933.  
  934. (set-pprint-dispatch 'ratio (formatter "#.~/div-print/"))
  935.  
  936. (set-pprint-dispatch '(and ratio (satisfies minusp))
  937.   (formatter "#.(- ~/div-print/)")
  938.   5)
  939.  
  940. (pprint '(1/3 -2/3)) prints: (#.(/ 1 3) #.(- (/ 2 3)))
  941.  
  942. The following two forms illustrate the specification of pretty printing
  943. functions for particular types of Lisp code. The first form illustrates how to
  944. specify the traditional method for printing quoted objects using ``''' syntax.
  945. Note the care taken to ensure that data lists that happen to begin with quote
  946. will be printed readably. The second form specifies that lists beginning with
  947. the symbol my-let should print the same way that lists beginning with let print
  948. when the initial pprint dispatch table is in effect.
  949.  
  950. (set-pprint-dispatch '(cons (member quote))
  951.   #'(lambda (s list)
  952.       (if (and (consp (cdr list)) (null (cddr list)))
  953.           (funcall (formatter "'~W") s (cadr list))
  954.           (pprint-fill s list)))))
  955.  
  956. (set-pprint-dispatch '(cons (member my-let))
  957.   (pprint-dispatch '(let) nil))
  958.  
  959. The next example specifies a default method for printing lists that do not
  960. correspond to function calls. Note that, as shown in the definition of
  961. pprint-tabular above, pprint-linear, pprint-fill, and pprint-tabular are
  962. defined with optional colon and atsign arguments so that they can be used as
  963. pprint dispatch functions as well as ~/.../ functions.
  964.  
  965. (set-pprint-dispatch
  966.   '(cons (not (and symbol (satisfies fboundp))))
  967.   #'pprint-fill
  968.   -5)
  969.  
  970. With a line length of 9, (pprint '(0 b c d e f g h i j k)) prints:
  971.  
  972. (0 b c d
  973.  e f g h
  974.  i j k)
  975.  
  976. This final example shows how to define a pretty printing function for a user
  977. defined data structure.
  978.  
  979. (defstruct family mom kids)
  980.  
  981. (set-pprint-dispatch 'family
  982.   #'(lambda (s f)
  983.       (format s "~@<#<~;~W and ~2I~_~/pprint-fill/~;>~:>"
  984.               (family-mom f) (family-kids f))))
  985.  
  986. The pretty printing function for the structure family specifies how to adjust
  987. the layout of the output so that it can fit aesthetically into a variety of
  988. line widths. In addition, it obeys the printer control variables *print-level*,
  989. *print-length*, *print-lines*, *print-circle*, *print-shared*, and
  990. *print-escape*, and can tolerate several different kinds of malformity in the
  991. data structure. The output below shows what is printed out with a right margin
  992. of 25, *print-pretty* t, *print-escape* nil, and a malformed kids list.
  993.  
  994. (write (list 'principal-family
  995.              (make-family :mom "Lucy"
  996.                           :kids '("Mark" "Bob" . "Dan")))
  997.        :right-margin 25 :pretty T :escape nil :miser-width nil)
  998.  
  999. (PRINCIPAL-FAMILY
  1000.  #<Lucy and
  1001.      Mark Bob . Dan>)
  1002.  
  1003. Note that a pretty printing function for a structure is different from the
  1004. structure's print function. While print functions are permanently associated
  1005. with a structure, pretty printing functions are stored in pprint dispatch
  1006. tables and can be rapidly changed to reflect different printing needs. If there
  1007. is no pretty printing function for a structure in the current print dispatch
  1008. table, the print function (if any) is used instead.
  1009.  
  1010. [change_end]
  1011.  
  1012. -------------------------------------------------------------------------------
  1013.  
  1014.  
  1015.  
  1016.  
  1017.  
  1018.